import re

from lxml.html import parse
from io import StringIO
import subprocess

import pagamigo.validator as Validator
from pagamigo.captcha import handle_captcha
from pagamigo.helpers import ProgressBar

ID = "login"

ARGS = {
    "username": ("Username (email address)", "username", Validator.email),
    "password": ("Password", "password", lambda x: len(x) > 0),
    "country": ("Country", "country", None),
}


def flow(session, username, password, country, debug=False):
    session.set_referer("/us/home")
    progress_bar = ProgressBar('Login', 2)

    auth_url = "/signin?country.x=" + country + "&locale.x=" + "en_US"
    auth_page = session.send_request(auth_url, {}, plain_headers=True)
    progress_bar.update(debug)

    session.referer = auth_url
    resp = session.send_request(auth_url, {
        "_csrf": re.search('_csrf" value="(.*?)"', auth_page).group(1),
        "locale.x": "en_US",
        "processSignin": "main",
        "fn_sync_data": "fn_sync_data",
        "intent": "signin",
        "ads-client-context": "signin",
        "requestUrl": auth_url,
        "forcePhonePasswordOptIn": "",
        "login_email": username,
        "login_password": password,
        "btnLogin": "Login",
        "splitLoginContext": "inputPassword",
        "splitLoginCookiedFallback": "true"
    }, mode="post_form", plain_headers=True)

    progress_bar.update(debug)

    return handle_captcha(session, resp)
